<?php

defined('__MAPEXEC__') or die('No direct access allowed');

class Maps_Map_Legend {
  
  private $count = null;
  private $images = null;
  private $descriptions = null;
  private $pointer = null;
  
  /**
   * Class constructor
   * @param   void
   * @return  void
   */
  public function __construct() {
    $this->images = array();
    $this->descriptions = array();
    $this->count = 0;
    $this->pointer = 0;
  }
  
  /**
   * Adds an item to the legend.
   * @param   String    URL to an image
   * @param   String    Legend description
   * @return  Integer   Index at which this item was inserted.
   */
  public function addItem($image, $description) {
    if ( empty($image) || empty($description) ) {
      return -1;
    }
    $this->images[] = $image;
    $this->descriptions[] = $description;
    $this->count++;
    return $this->count - 1;
  }
  
  /**
   * Gets an item in this legend.
   * @param   Integer   Legend item index
   * @return  Array     Legend item info
   */
  public function getItem($index = -1) {
    if ( !$this->itemExists($index) ) {
      return null;
    }
    return array('image'=>$this->images[$index], 'description'=>$this->descriptions[$index]);
  }
  
  /**
   * Detects if a legend item index exists
   * @param   Integer   Legend item index
   * @return  Boolean   True if index exists
   */
  private function itemExists($index) {
    return $index >= 0 && $index < $this->count ? true : false;
  }
  
  /**
   * Moves pointer to the next legend item
   * @param   void
   * @return  Array   Legend item info or null if at end of the list.
   */
  public function next() {
    $item = $this->getItem($this->pointer);
    if ( isset($item) ) {
      $this->pointer++;
    } else {
      $this->pointer = 0;
    }
    return $item;
  }
  
  /**
   * Removes an item from the legend.
   * @param   Integer   Legend index
   * @return  Integer   New legend item count
   */
  public function removeItem($index) {
    if ( !$this->itemExists($index) ) {
      return;
    }
    array_splice($this->images, $index, 1);
    array_splice($this->descriptions, $index, 1);
    $this->count--;
    return $this->count;
  }
  
}

?>